//
//  CommentDetailViewController.m
//  myhuibao
//
//  Created by lijun on 13-4-3.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "CommentDetailViewController.h"
#import <UIKit/UIKit.h>
#import "Config.h"
#import "SBJson.h"
#import "RestaurantDetailViewController.h"
#import "RatingView.h"
#import "CommentsViewController.h"
#import<QuartzCore/QuartzCore.h>

@interface CommentDetailViewController ()

@end

@implementation CommentDetailViewController
@synthesize merchantName;
@synthesize values;
@synthesize dealId;
@synthesize commentDeatil;
@synthesize saveBtn;
@synthesize type;
@synthesize comments;
@synthesize reqDetail;
static bool errormerchant=NO;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    if(comments==nil){
//     [self getMerchant:_merchantId];
     if(errormerchant==YES){
            return;
     }
     [self getCommentDetail];
     values=[[NSMutableDictionary alloc] init];
    }else{
        [self getCommentDetails];
    }
    
    // Do any additional setup after loading the view.
    [self addCloseBar];
    commentDeatil.layer.cornerRadius=5;
    commentDeatil.layer.borderWidth=1;
    commentDeatil.layer.borderColor=[UIColor lightGrayColor].CGColor;
    [[commentDeatil layer] setShadowOffset:CGSizeMake(1, 1)];
    [[commentDeatil layer] setShadowRadius:3];
    [[commentDeatil layer] setShadowOpacity:1];
    [[commentDeatil layer] setShadowColor:[UIColor lightGrayColor].CGColor];
    

    commentDeatil.delegate = self;
    }
- (void) getMerchant:(int) merchantId
{
    //异步请求
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?merchantID=%d",url_detail,merchantId]] ;
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate: self];
    [request startSynchronous ];
    NSError *error = [request error ];
    assert (!error);
    // 如果请求成功，返回 Response
    NSString *response = [request responseString ];
    NSDictionary *dic=[response JSONValue];
    if([[dic valueForKey:@"status"] isEqualToString:@"ERROR"]){
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE
                                                     message:@"错误的餐厅信息"
                                                    delegate:nil
                                           cancelButtonTitle:@"确定"
                                           otherButtonTitles:nil];
        [alert show];
        errormerchant=YES;
        commentDeatil.hidden=YES;
        saveBtn.hidden=YES;
        return;
    }else{
    NSDictionary *data=[dic valueForKey:@"data"];
    NSString *smerchantName=[data valueForKey:@"NAME"];
    merchantName.text=smerchantName;
    errormerchant=NO;
    commentDeatil.hidden=NO;
    saveBtn.hidden=NO;
    }
   // NSLog ( @"%@" ,response);
}
-(void) getCommentDetail{
    NSURL *url=[NSURL URLWithString:url_commentDeatil];
    reqDetail=[ASIFormDataRequest requestWithURL:url];
    [reqDetail setPostValue:[NSString stringWithFormat:@"%d",_merchantType] forKey:@"orderTypeID"];
    [reqDetail setDelegate:self];
    [reqDetail startAsynchronous];

    type=2;
}

-(void) getCommentDetails{
    NSURL *url=[NSURL URLWithString:url_commentDeatil];
    reqDetail=[ASIFormDataRequest requestWithURL:url];
    [reqDetail setPostValue:[NSString stringWithFormat:@"%d",_merchantType] forKey:@"orderTypeID"];
    [reqDetail setDelegate:self];
    
    [reqDetail startAsynchronous];

    type=5;
}
- (void)viewDidUnload
{
    if(comments==nil){
     [self setMerchantName:nil];
     [self setCommentDeatil:nil];
     [super viewDidUnload];
     }
    // Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

//异步请求的二个方法
-(void) requestFinished:(ASIFormDataRequest *)request
{
    NSString *jsonStr=[request responseString];
    NSDictionary *dic=[jsonStr JSONValue];
    if([@"ERROR" isEqualToString:[dic valueForKey:@"status"]]){
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE
                message:@"获取信息失败,请检查网络"
                delegate:nil
                cancelButtonTitle:@"确定"
                otherButtonTitles:nil];
        [alert show];
        return;
    }if([@"LOGIN" isEqualToString:[dic valueForKey:@"status"]]){
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE
                                                     message:@"非法操作,请重新登陆"
                                                    delegate:nil
                                           cancelButtonTitle:@"确定"
                                           otherButtonTitles:nil];
        [alert show];
        return;
    }
    NSDictionary *data=[dic valueForKey:@"data"];
    if(type==1)
    {
        NSString *smerchantName=[data valueForKey:@"NAME"];
        merchantName.text=smerchantName;
    }
    if(type==2){
        merchantName.text = _mName;
        int i=0;
        for(NSDictionary *row in data){
            i++;
          UILabel *lable= [[UILabel alloc]initWithFrame:CGRectMake(6, 45*i, 110, 30 )];
         lable.font = [UIFont fontWithName:@"Arial" size:14];
         lable.backgroundColor = [UIColor clearColor];
         lable.text = [row valueForKey:@"codeItemDescription"];
         [self.view addSubview:lable];
         RatingView *view=[[RatingView alloc]initWithFrame:CGRectMake(115,45*i,115,30)];
        [view
         setImagesDeselected:@"0.png"
         partlySelected:@"1.png" fullSelected:@"2.png" andDelegate:self];
            [view displayRating:0
                  setCodeItemId:[[row valueForKey:@"codeItemID"]intValue]];
            [self.view addSubview:view];
        }
        UILabel *agreelbl= [[UILabel alloc]initWithFrame:CGRectMake(6, 45*(i+1), 110, 30 )];
        agreelbl.font = [UIFont fontWithName:@"Arial" size:14];
        agreelbl.backgroundColor = [UIColor clearColor];
        agreelbl.text = @"综合评分";
        [self.view addSubview:agreelbl];
        RatingView *agreeview=[[RatingView alloc]initWithFrame:CGRectMake(115,45*(i+1),115,30)];
        [agreeview
         setImagesDeselected:@"0.png"
         partlySelected:@"1.png" fullSelected:@"2.png" andDelegate:self];
        [agreeview displayRating:0
              setCodeItemId:0];
        [self.view addSubview:agreeview];
    }if (type==3) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:APP_TITLE message:[dic valueForKey:@"data"]  delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        CommentsViewController *view=[[CommentsViewController alloc]initWithNibName:@"CommentsViewController" bundle:nil];
        [self.navigationController pushViewController:view animated:YES];
    }if (type==5&&comments!=nil) {
            int i=0;
            for(NSDictionary *row in data){
                i++;
                float star=0.0;
                UILabel *lable= [[UILabel alloc]initWithFrame:CGRectMake(6, 45*i, 110, 30 )];
                lable.font = [UIFont fontWithName:@"Arial" size:14];
                lable.backgroundColor = [UIColor clearColor];
                lable.text = [row valueForKey:@"codeItemDescription"];
                star=[[comments objectForKey:[NSString stringWithFormat:@"%d",i]] floatValue];
                [self.view addSubview:lable];
                RatingView *view=[[RatingView alloc]initWithFrame:CGRectMake(115,45*i,115,30)];
                view.canchange=YES;
                [view
                 setImagesDeselected:@"0.png"
                 partlySelected:@"1.png" fullSelected:@"2.png" andDelegate:self];
                [view displayRating:star
                      setCodeItemId:[[row valueForKey:@"codeItemID"]intValue]];
                [self.view addSubview:view];
            }
            UILabel *agreelbl= [[UILabel alloc]initWithFrame:CGRectMake(6, 45*(i+1), 110, 30 )];
            agreelbl.font = [UIFont fontWithName:@"Arial" size:14];
            agreelbl.backgroundColor = [UIColor clearColor];
            agreelbl.text = @"综合评分";
            [self.view addSubview:agreelbl];
            RatingView *agreeview=[[RatingView alloc]initWithFrame:CGRectMake(115,45*(i+1),115,30)];
            agreeview.canchange=YES;
            [agreeview
             setImagesDeselected:@"0.png"
             partlySelected:@"1.png" fullSelected:@"2.png" andDelegate:self];
        [agreeview displayRating:[[comments objectForKey:@"AGREE"]floatValue]
                       setCodeItemId:0];
            [self.view addSubview:agreeview];
        NSString *str=[comments objectForKey:@"CONTENT"];
        if((NSNull *)str == [NSNull null]){
//            commentDeatil.placeholder=@"您没有输入此次交易的评论哦!";
        }else{
            commentDeatil.text=[comments objectForKey:@"CONTENT"];
        }
//        commentDeatil.userInteractionEnabled=NO;
        [commentDeatil resignFirstResponder];
        saveBtn.hidden=YES;
        NSString *smerchantName=[comments valueForKey:@"MERCHANT_NAME"];
        merchantName.text=smerchantName;
    }
}

-(void)ratingChanged:(float)newRating setCodeItemId:(int)codeItemId{
    NSString *value=[NSString stringWithFormat:@"%1.1f",newRating];
   [values removeObjectForKey:[NSString stringWithFormat:@"%i", codeItemId]];
    [values setValue:value forKey:[NSString stringWithFormat:@"%i", codeItemId]];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
}

- (IBAction)merchantDetail:(id)sender {
    RestaurantDetailViewController *view=[[RestaurantDetailViewController alloc]initWithNibName:@"RestaurantDetailViewController" bundle:nil];
    if(comments!=nil){
        self.merchantId=[[comments objectForKey:@"MERCHANT_ID"]intValue];
    }
    view.merchantId =self.merchantId;
    view.merchantType=_merchantType;
    view.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:view animated:NO];
}

- (IBAction)saveCommects:(id)sender {
    if(commentDeatil.text.length<1){
        UIAlertView *view=[[UIAlertView alloc]initWithTitle:APP_TITLE message:@"评论内容为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [view show];
        return;
    }
    NSString *strcomments=[[NSString alloc] init];
    [values removeObjectForKey:@"0"];
    if (values.count <4) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示"
                                                     message:@"评分数据不完整哦!亲"
                                                    delegate:nil
                                           cancelButtonTitle:@"确定"
                                           otherButtonTitles:nil];
        [alert show];
        return;
    }

    for(int i=0;i<[values count]-1;i++){
       NSString *sid=[NSString stringWithFormat:@"%d",(i+1)];
        NSString *value=[values objectForKey:sid];
        if([value isEqualToString:@"0.0"]){
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示"
                message:@"评分数据不完整哦!亲"
                delegate:nil
                cancelButtonTitle:@"确定"
                otherButtonTitles:nil];
            [alert show];
            return;
        }else{
            strcomments=[strcomments stringByAppendingString:[NSString stringWithFormat:@"%i:%d,",(i+1),[value intValue]]];
        }
//        if(i>=([values  count]-2))
//            break;
    }
    strcomments= [strcomments substringToIndex:[strcomments length] - 1];
    NSURL *url=[NSURL URLWithString:url_savecomment];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request setPostValue:[NSString stringWithFormat:@"%i", [[Config Instance] getMemberId]] forKey:@"memberID"];
    [request setPostValue:[[Config Instance] getPassword] forKey:@"password"];
    [request setPostValue:[NSString stringWithFormat:@"%i",dealId] forKey:@"dealID"];
    [request setPostValue:strcomments forKey:@"grade"];
    [request setPostValue:commentDeatil.text forKey:@"content"];
    int count=[values count];
    int agree=[[values objectForKey:[NSString stringWithFormat:@"%d",count]] intValue];
    [request setPostValue:[NSString stringWithFormat:@"%d",agree]  forKey:@"agree"];
    [request setDelegate:self];
    [request startAsynchronous];
    type=3;
}

- (IBAction)goBack:(id)sender {
    
    [super.navigationController
     popViewControllerAnimated:YES];
}
- (IBAction)endEdit:(id)sender {
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
    self.view.frame = rect;
    [UIView commitAnimations];
    [commentDeatil resignFirstResponder];
}
- (IBAction)startEdit:(id)sender {
    float height = 256.0;
    CGRect frame = self.view.frame;
    frame.origin.y=(frame.size.height-self.saveBtn.frame.size.height-self.saveBtn.frame.origin.y)-height;
    [UIView beginAnimations:@"Curl"context:nil];//动画开始
    [UIView setAnimationDuration:0.30];
    [UIView setAnimationDelegate:self];
    [self.view setFrame:frame];
    [UIView commitAnimations];
}
- (void)addCloseBar{
    UIToolbar * topView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
    [topView setBarStyle:UIBarStyleDefault];
    
    UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard)];
    NSArray * buttonsArray = [NSArray arrayWithObjects:btnSpace, doneButton, nil];
    
    [topView setItems:buttonsArray];
    [commentDeatil setInputAccessoryView:topView];
}
-(IBAction)dismissKeyBoard
{
//    [commentDeatil resignFirstResponder];
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    CGRect rect = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, self.view.frame.size.height);
    self.view.frame = rect;
    [UIView commitAnimations];
    [commentDeatil resignFirstResponder];

}
- (void)textViewDidBeginEditing:(UITextView *)textView{
    float height = 256.0;
    CGRect frame = self.view.frame;
    frame.origin.y=(frame.size.height-self.saveBtn.frame.size.height-self.saveBtn.frame.origin.y)-height;
    [UIView beginAnimations:@"Curl"context:nil];//动画开始
    [UIView setAnimationDuration:0.30];
    [UIView setAnimationDelegate:self];
    [self.view setFrame:frame];
    [UIView commitAnimations];

}

@end
